# @Time : 2021/4/3 11:46
# @Author : Fioman 
# @Phone : 13149920693
"""
主要用来统计代码行数,整个项目中的所有的代码行数统计.
"""
from settings import BASE_DIR
import os
import time


def get_now_time_str():
    timeNow = time.time()
    now = time.strftime("%Y-%m-%d %H-%M-%S", time.localtime(timeNow))
    return now


def count_code_lines(filePath):
    blank = 0  # 空行
    code = 0  # 代码
    note = 0  # 注释
    manyNoteFlag = False  # 多行注释
    with open(filePath, encoding="utf-8") as f:
        while True:
            line = f.readline()
            if not line:
                break
            if manyNoteFlag:
                note += 1
                if line.strip().startswith('"""') or line.strip().startswith("'''"):
                    manyNoteFlag = False
                    continue
                else:
                    continue
            if len(line.strip()) == 0:
                blank += 1
            elif line.strip().startswith("#") or line.strip().startswith("//"):
                note += 1
            elif line.strip().startswith('"""') or line.strip().startswith("'''"):
                # 这个地方读到了多行注释,需要将多行注释的标志打开
                note += 1
                manyNoteFlag = True
                continue
            else:
                code += 1
    return blank, code, note


def get_last_count_record(line):
    """
    获取文件上上一次的统计结果,如何获取拆分数据.
    :param line:
    :return:
    """
    lineSplit = line.strip().split(":")
    code = int(lineSplit[1].split(",")[0])
    note = int(lineSplit[2].split(",")[0])
    blank = int(lineSplit[3].split(",")[0])
    return code, note, blank


def get_time_by_time_str(timeStr):
    """
    根据时间的字符串,获取具体的月份天数和小时以及分
    :param timeStr: 类似"2021-04-03 13-34-46"这样的时间字符串
    :return:
    """
    month = timeStr[5:7]
    day = timeStr[8:10]
    hour = timeStr[11:13]
    minute = timeStr[14:16]
    if month.startswith("0"):
        monthList = list(month)
        monthList.pop(0)
        month = ''.join(monthList)

    if day.startswith("0"):
        dayList = list(day)
        dayList.pop(0)
        day = ''.join(dayList)

    if hour.startswith("0"):
        hourList = list(hour)
        hourList.pop(0)
        hour = ''.join(hourList)

    if minute.startswith("0"):
        minuteList = list(minute)
        minuteList.pop(0)
        minute = ''.join(minuteList)

    return int(month), int(day), int(hour), int(minute)


def count_debug_time_offset(line):
    """
    获取两次代码统计耗费时间
    :param line:
    :return:
    """
    nowTime = get_now_time_str()
    month, day, hour, minute = get_time_by_time_str(nowTime)
    lastMonth, lastDay, lastHour, lastMinute = get_time_by_time_str(line[:19])
    # 计算时间间隔.
    monthDuration = month - lastMonth
    dayDuration = day - lastDay
    hourDuration = hour - lastHour
    minuteDuration = minute - lastMinute

    if minuteDuration < 0:
        minuteDuration = 60 + minuteDuration
        hourDuration -= 1
    if hourDuration < 0:
        hourDuration += 24
        dayDuration -= 1
    if dayDuration < 0:
        dayDuration += 30
        monthDuration -= 1
    timeDuration = "{} 月 {} 天 {} 小时 {} 分".format(
        monthDuration, dayDuration, hourDuration, minuteDuration)
    return timeDuration


if __name__ == '__main__':
    countCodeRecordPath = os.path.join(BASE_DIR, r"personal_tools\code_count_record")
    # 如果文件不存在就创建
    try:
        f1 = open(countCodeRecordPath, 'r')
        f1.close()
    except IOError:
        f2 = open(countCodeRecordPath, "w")
    pyEndFiles = []
    jsEndFiles = []  # 然后就是统计js文件,将js文件也统计进来
    jsDir = BASE_DIR.replace("python", r"src\pages\HengDing")

    # 1.首先是列出来当前项目的所有的.py文件
    for root, dirs, files in os.walk(BASE_DIR):
        for file in files:
            if file[-3:] != ".py" or file == "__init__.py":
                continue
            pyEndFiles.append(os.path.join(root, file))

    for root, dirs, files in os.walk(jsDir):
        for file in files:
            if file[-3:] != ".js":
                continue
            pyEndFiles.append(os.path.join(root, file))

    allBlank, allCode, allNote = 0, 0, 0
    for filePathOuter in pyEndFiles:
        fileDir, fileName = os.path.split(filePathOuter)
        blankOuter, codeOuter, noteOuter = count_code_lines(filePathOuter)
        allBlank += blankOuter
        allCode += codeOuter
        allNote += noteOuter
        print("文件 {} 的代码统计结果: 代码 = {},注释 = {},空白 = {}".format(fileName, codeOuter, noteOuter, blankOuter))

    print("整个项目统计结果: 代码 = {},注释 = {},空白 = {}".format(allCode, allNote, allBlank))
    # 将代码的统计记录写入到代码统计记录中
    with open(countCodeRecordPath, 'r', encoding='utf-8') as fOuter:
        lines = fOuter.readlines()
        if len(lines) != 0:
            # 上一次的结果
            lastCode, lastNote, lastBlank = get_last_count_record(lines[-1])
            allCodeAdd = allCode - lastCode
            allNoteAdd = allNote - lastNote
            allBlankAdd = allBlank - lastBlank
            timeOffst = count_debug_time_offset(lines[-1])

        else:
            allCodeAdd = allCode
            allNoteAdd = allNote
            allBlankAdd = allBlank
            timeOffst = "{} 月 {} 天 {} 小时 {} 分".format(0,0,0,0)

    with open(countCodeRecordPath, 'a', encoding='utf-8') as fOuter:
        fOuter.write(get_now_time_str() + " 项目统计结果 代码: {},注释: {},空白: {}, 增加: 代码 {},注释 {},空白 {},距离上次统计:{} \n".format(
            allCode, allNote, allBlank, allCodeAdd, allNoteAdd, allBlankAdd, timeOffst))
